/*
 * Copyright (c) 2011 Auzingers
 * Created by Oui-IT
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.auzingers.docsorganizer.googleapi;

import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.services.calendar.CalendarRequestInitializer;

import android.content.Context;

import java.io.IOException;
import java.net.HttpURLConnection;

/**
 * Class necessary to initialize a google docs request.
 */
public class GoogleDocsAndroidRequestInitializer extends CalendarRequestInitializer {

    private static final HttpTransport TRANSPORT = AndroidHttp.newCompatibleTransport();

    private String authToken;

    private GooglePreferencesUtil preferences;

    private GoogleAccountManager accountManager;

    /**
     * Create a new instanceof GoogleDocsandroidRequestInitializer.
     * @param ctx current context
     * @param accountManager current account manager
     */
    public GoogleDocsAndroidRequestInitializer(Context ctx, GoogleAccountManager accountManager) {
        super(TRANSPORT);
        preferences = GooglePreferencesUtil.getInstance(ctx);
        authToken = preferences.getAuthToken();
        this.accountManager = accountManager;
        setGsessionid(preferences.getGSessionId());
    }

    public void setAuthToken(String token) {
        authToken = token;
    }

    public String getAuthToken() {
        return authToken;
    }

    @Override
    public void intercept(HttpRequest request) throws IOException {
        super.intercept(request);
        request.getHeaders().setAuthorization(GoogleHeaders.getGoogleLoginValue(authToken));
    }

    @Override
    public boolean handleResponse(HttpRequest request, HttpResponse response, boolean retrySupported)
            throws IOException {
        switch (response.getStatusCode()) {
            case HttpURLConnection.HTTP_MOVED_TEMP:
                super.handleResponse(request, response, retrySupported);
                preferences.setGSessionId(getGsessionid());
                return true;
            case HttpURLConnection.HTTP_UNAUTHORIZED:
                accountManager.invalidateAuthToken(authToken);
                authToken = null;
                preferences.clearAuthToken();
                return false;
            default:
                return false;
        }
    }
}
